<script setup>
import { onMounted, ref, onUnmounted } from 'vue'
import axios from '@/http/index'
import dayjs from 'dayjs'
import AMapLoader from '@amap/amap-jsapi-loader';

const onClickLeft = () => history.back();
let id = ref(localStorage.getItem('houseid'))
let order = ref([])
let housexq = ref([])
let haddress = ref('')
let map = null;
let marker = null; // 定义标记变量

onUnmounted(() => {
    map?.destroy();
});

onMounted(() => {
    axios.get(`/my/houseorder`).then(res => {
        if (res.data.code == 200) {
            order.value = res.data.data
        }
    });
    
    axios.get(`/my/housexq?id=${id.value}`).then(res => {
        if (res.data.code == 200) {
            haddress.value = res.data.data[0].address
            housexq.value = res.data.data
            console.log(haddress.value);
            // 在这里调用 getLocation 以便在获取地址后立即标记
            getLocation(); // 直接在这里调用
        }
    });

    window._AMapSecurityConfig = {
        securityJsCode: "70b6c6e62f3dfc7e41364addec168027",
    };
    
    AMapLoader.load({
        key: "bb2bbb09e41352a763271404dfbd5bc1",
        version: "2.0",
        plugins: ["AMap.Scale", "AMap.ToolBar", "AMap.ControlBar", "AMap.HawkEye", "AMap.Geocoder", "AMap.GeoLocation"],
    }).then((AMap) => {
        // 地图加载
        map = new AMap.Map("container", {
            pitch: 20,
            viewMode: "3D",
            rotateEnable: true,
            pitchEnable: true,
            zoom: 17,
            rotation: -15,
            zooms: [2, 20],
        });

        const geolocation = new AMap.Geolocation({
            enableHighAccuracy: true,
            timeout: 10000,
            buttonPosition: "LB",
            buttonOffset: new AMap.Pixel(10, 20),
            showMarker: true,
            showCircle: true,
            panToLocation: true,
            zoomToAccuracy: true,
        });

        map.addControl(geolocation);
        geolocation.getCurrentPosition(); // 开始定位
    }).catch(e => {
        console.log(e);
    });
});

const getLocation = () => {
    AMapLoader.load({
        key: "bb2bbb09e41352a763271404dfbd5bc1",
        version: "2.0",
        plugins: ["AMap.Geocoder"],
    }).then((AMap) => {
        AMap.plugin("AMap.Geocoder", function () {
            var geocoder = new AMap.Geocoder();
            geocoder.getLocation(haddress.value, function (status, result) {
                if (status === "complete" && result.info === "OK") {
                    let lng = result.geocodes[0].location.lng;
                    let lat = result.geocodes[0].location.lat;
                    const degree = [lng, lat];
                    map.setCenter(degree); // 设置地图中心点

                    // 如果标记已存在，则先移除
                    if (marker) {
                        map.remove(marker);
                    }

                    // 创建新的标记
                    marker = new AMap.Marker({
                        position: degree, // 标记位置
                        icon: "https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png", // 红色标记图标
                        title: haddress.value, // 标记标题
                    });
                    map.add(marker); // 将标记添加到地图上

                    // 添加鼠标悬停事件
                    marker.on('mouseover', function () {
                        const infoWindow = new AMap.InfoWindow({
                            content: `<div style="padding:5px;">当前位置: ${haddress.value}</div>`,
                            offset: new AMap.Pixel(0, -30) // 信息窗口的偏移量
                        });
                        infoWindow.open(map, marker.getPosition()); // 在标记位置打开信息窗口
                    });

                    // 添加鼠标移出事件
                    marker.on('mouseout', function () {
                        map.clearInfoWindow(); // 清除信息窗口
                    });
                } else {
                    alert("地址解析失败，请检查地址是否正确");
                }
            });
        });
    });
}

</script>

<template>
    <div>
        <van-sticky>
            <van-nav-bar title="订单详情" left-arrow @click-left="onClickLeft" />
        </van-sticky>
        <div style="padding-left:40px;margin-top:10px;" v-for="item in order.slice(-1)" :key="item._id">
            <p style="position:relative;">
                <span>订单号</span>
                <span style="margin-left:43px;">G{{ item._id.slice(15) }}</span>
                <span style="color:red;position:absolute;right:25px;">待酒店确认</span>
            </p>
            <p style="text-align:center;margin-left:-20px;margin-top:40px;">君假酒店（千山城规站店）</p>
            <P style="margin-top:40px;">
                <span>入住:&nbsp;{{ dayjs(item.entertime).format('MM月DD日') }}</span>
                <span style="margin-left:20px;">共&nbsp;{{ item.days }}&nbsp;晚</span>
                <span style="margin-left:20px;">离开:&nbsp;{{ dayjs(item.leavetime).format('MM月DD日') }}</span>
            </P>
            <div id="container"></div>
            <p style="display: flex;margin-left:-20px;margin-top:20px;color:gray;">
                <el-icon :size="30" style="vertical-align: middle;"><MapLocation /></el-icon>
                <input id="tipinput" style="border:0;width:400px;font-size:15px;" :value="haddress">
            </p>
            <p style="margin-top:20px;">
                <span style="color:gray;">入住人:</span>
                <span style="margin-left:10px;">{{ item.entername }}</span>
            </p>
            <p style="margin-top:20px;font-size:17px;">
                <span style="color:gray;">联系方式：</span>
                <span>{{ item.phone }}</span>
            </p>
            <div v-for="items in housexq" :key="items._id">
                <h3 style="font-weight:bolder;margin-top:30px;">发票信息</h3>
                <p style="margin-top:30px;">
                    <span style="color:gray;">发票明细</span>
                    <span style="margin-left:60px;">押金</span>
                    <span style="margin-left:60px;">￥200.00</span>
                </p>
                <p style="margin-top:30px;">
                    <span style="color:gray;">发票抬头</span>
                    <span style="margin-left:60px;">{{ items.cate }}嘻嘻哈哈股份有限公司</span>
                </p>
                <p style="margin-top:30px;">
                    <span style="color:gray;">纳税人识别号</span>
                    <span style="margin-left:30px;">{{ items._id.slice(10) }}</span>
                </p>
                <div style="margin-top:30px;display:flex;">
                    <p style="color:gray;">配送信息</p>
                    <div style="margin-left:60px;">
                        <p>
                            <span>{{ item.entername }}</span>
                            <span style="margin-left:20px;">{{ item.phone }}</span>
                        </p>
                        <p>{{ items.address.split('市')[1] }}</p>
                    </div>
                </div>
            </div>
            <div style="margin-top:40px;">
                <p style="position:relative;font-size:17px;">
                    <span>支付方式</span>
                    <span style="position:absolute;right:30px;">{{ item.pay }}</span>
                </p>
                <p style="color:#C9C9C9;margin-left:-30px;">—— —— —— —— —— —— —— —— —— ——— —</p>
                <p v-for="itema in housexq" :key="itema._id" style="position:relative;">
                    <span style="color:gray;">房间费</span>
                    <span style="position:absolute;right:30px;">￥{{ itema.price }}.0</span>
                </p>
                <p style="font-size:17px;margin-left:200px;margin-top:10px;margin-bottom:10px;">实付款：<span
                        style="color:red;font-weight:bolder;">￥{{ item.price }}.0</span></p>
                <p style="font-size:17px;margin-left:80px;">下单时间：{{ dayjs(item.ordertime).format('YYYY-MM-DD HH:mm:ss')
                    }}
                </p>
            </div>
            <div style="margin-top:30px;padding-bottom:20px;">
                <van-button style="margin-left:30px;" plain hairline type="primary" @click="$router.push(`/home/payerror?id=${item._id}`)">取消订单</van-button>
                <van-button style="margin-left:50px;" type="primary" @click="$router.push(`/home/xq?id=${id}`)">再次预订</van-button>
            </div>
        </div>
    </div>
</template>

<style scoped>
#container {
    width: 100%;
    height: 200px;
    margin-left: -20px;
}
</style>
